//
//  CZComposeTextView.swift
//  WeiBO28
//
//  Created by 飞奔的羊 on 16/5/19.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

//自定义 textView

//实时看到 xib 效果
@IBDesignable
class CZComposeTextView: UITextView {
	
	// MARK: ------站位文字------
	private lazy var placeHolderLabel: UILabel = {
	let labele = UILabel()
	labele.font = UIFont.systemFontOfSize(12)
		 labele.text = "听说下雨天音乐和辣条很配哟"
		labele.numberOfLines = 0
		labele.sizeToFit()
		labele.textColor = UIColor.lightGrayColor()
	
	return labele
	}()
	//让属性在 xib 中编译
	@IBInspectable var placeHoder: String? {
		didSet{
		placeHolderLabel.text = placeHoder
//			placeHolderLabel.sizeToFit()
		}
	}
	
	//重写 font
	override var font: UIFont? {
		didSet{
			if font == nil {
			return
			}
		placeHolderLabel.font = font
		
		}
	}
	//重写 TEXT
	override var text: String? {
		didSet{
		
		placeHolderLabel.hidden = hasText()
		}
	}
	
	override init(frame: CGRect, textContainer: NSTextContainer?) {
		super.init(frame: frame, textContainer: textContainer)
		setUpUI()
		//监听文字改变的通知
		NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CZComposeTextView.textChange), name: UITextViewTextDidChangeNotification, object: nil)
		
	}
	
	
	//支持 xib
	required init?(coder aDecoder: NSCoder) {
		super.init(coder: aDecoder)
		setUpUI()
		//监听文字改变的通知
		NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CZComposeTextView.textChange), name: UITextViewTextDidChangeNotification, object: nil)
	}

	private func setUpUI() {
	addSubview(placeHolderLabel)
	
		
		//使用系统的约束
		placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
		
		addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: -10))
		
	}
	
	override func layoutSubviews() {
		super.layoutSubviews()
		
		//指定位置
		placeHolderLabel.frame.origin.x = 5
		placeHolderLabel.frame.origin.y = 8
	}
	
	@objc private func textChange() {
//		if hasText() {
//			placeHolderLabel.hidden = true
//		} else {
//		placeHolderLabel.hidden = false
//		}
		
		placeHolderLabel.hidden = hasText()
	
	}
	//移除通知
	deinit {
	
	NSNotificationCenter.defaultCenter().removeObserver(self)
	}
	
}
















